package PerfectRectangle;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;


public class Solution {

    public boolean isRectangleCover(int[][] rectangles) {
    	HashMap<String,Integer> map=new  HashMap<>();
    	int realCover=0,shouldCover=0;
    	for (int i=0;i<rectangles.length;i++){
    		List<String> point=new ArrayList<>();
    		point.add(rectangles[i][0]+" "+rectangles[i][1]);
    		point.add(rectangles[i][2]+" "+rectangles[i][1]);
    		point.add(rectangles[i][0]+" "+rectangles[i][3]);
    		point.add(rectangles[i][2]+" "+rectangles[i][3]);
    		point.forEach(pointT->{
        		Integer count=map.get(pointT);
        		if (count==null) map.put(pointT, 1);
        		else map.remove(pointT); 			
    		});
    		realCover=realCover+(rectangles[i][2]-rectangles[i][0])*(rectangles[i][3]-rectangles[i][1]);
    	}
    	if (map.keySet().size()!=4) return false;
    	else{
    		int minx=Integer.MAX_VALUE,miny=Integer.MAX_VALUE,maxx=0,maxy=0;
    		Iterator<String> iter=map.keySet().iterator();
    		while (iter.hasNext()){
    			String[] point=iter.next().split(" ");
    			minx=Math.min(minx, Integer.parseInt(point[0]));
    			miny=Math.min(miny, Integer.parseInt(point[1]));
    			maxx=Math.max(maxx, Integer.parseInt(point[0]));
    			maxy=Math.max(maxy, Integer.parseInt(point[1]));
    		}
    		shouldCover=(maxx-minx)*(maxy-miny);
    		if (shouldCover==realCover) return true;
    		else return false;
    	}
    	
    	
    }
    public static void main(String args[]) {
    	int[][] t={
    	           {1,1,3,3},
    	           {3,1,4,2},
    	           {3,2,4,4},
    	           {1,3,2,4},
    	           {2,3,3,4}
    	         };
	    Solution so=new Solution();
	    System.out.println(so.isRectangleCover(t));
	}
}
